import http from '@/utils/http'
import type {
  PaginationParams,
  PaginationResponse,
  Script,
  WorkflowResponse,
  Workflow,
} from './types'

interface CreateScriptParams {
  name: string
  content: string
  version: string
}

interface UpdateScriptParams {
  id: number
  name?: string
  content?: string
  version?: string
}

export interface Task {
  id: number
  name: string
  description: string
  execType: string
  execHost: string
  execUser: string
  status: string
  workOrderId: string
  createTime: string
  mediaType: string
  mediaId: number
  skipped: string[]
  resources: Array<{
    pod_name: string
    workflow: string
    status: string
    step: string
    uid: string
  }>
}

export const taskService = {
  // 获取脚本列表
  getScripts: (params: PaginationParams) => {
    return http.get<PaginationResponse<Script>>('/task/scripts', {
      params: {
        page: params.page,
        page_size: params.page_size,
      },
    })
  },

  // 获取单个脚本详情
  getScriptById: (id: number) => {
    return http.get<never, Script>(`/task/scripts/${id}`)
  },

  // 创建脚本
  createScript: (data: CreateScriptParams) => {
    return http.post<never, Script>('/task/scripts', data)
  },

  // 更新脚本
  updateScript: (data: UpdateScriptParams) => {
    return http.put<never, Script>('/task/scripts', data)
  },

  // 删除脚本
  deleteScript: (id: number) => {
    return http.delete<never, void>(`/task/scripts/${id}`)
  },

  // 下载脚本
  downloadScript: (id: number) => {
    return http.get<never, Blob>(`/task/scripts/${id}/download`, {
      responseType: 'blob',
    })
  },
  // 创建任务
  createTask: (data: Partial<Task>) => {
    return http.post<Task>('/task/tasks', data)
  },
  // 获取任务列表
  getTasks: (params: PaginationParams) =>
    http.get<PaginationResponse<Task>>('/task/tasks', {
      params: {
        page: params.page,
        page_size: params.page_size,
      },
    }),

  // 删除任务
  deleteTask: (id: number) => http.delete(`/task/tasks/${id}`),

  // 获取任务详情
  getTaskById: (id: number) => http.get<Task>(`/task/tasks/${id}`),

  // 获取工作流列表
  getWorkflows: (params: PaginationParams) => {
    return http.get<WorkflowResponse>('/task/workflows', {
      params: {
        page: params.page,
        page_size: params.page_size,
      },
    })
  },

  // 获取工作流详情
  getWorkflowById: (id: number) => {
    return http.get<Workflow>(`/task/workflows/${id}`)
  },

  // 创建工作流
  createWorkflow: (data: Partial<Workflow>) => {
    return http.post<Workflow>('/task/workflows', data)
  },

  // 更新工作流
  updateWorkflow: (data: Partial<Workflow>) => {
    return http.put<Workflow>('/task/workflows', data)
  },

  // 删除工作流
  deleteWorkflow: (id: number) => {
    return http.delete(`/task/workflows/${id}`)
  },
}
